package com.dong.es.entity.dtocast.base;

import co.elastic.clients.elasticsearch._types.SortOrder;
import com.dong.es.entity.EsBaseDTO;
import com.dong.es.entity.EsViewDTO;
import com.dong.es.entity.dtocast.DTOCastMethod;
import com.dong.es.entity.searchparam.order.EsFieldSortParam;
import org.apache.commons.lang3.StringUtils;

/**
 * 使用实例：@DTOCastAnno(sort = 920, paramFields = {"orderBy"}, method = DTOCastOrderBy.class)
 *
 * @description: 排序 转换
 * @author: 陈瑞东
 * @create: 2022-06-21 15:19
 */
public class DTOCastOrderBy extends DTOCastMethod {

    // 排序字段(例如："queryTime desc")
    private String orderBy;

    @Override
    protected Integer sizeLimit() {
        return 1;
    }

    @Override
    protected Class[] typeLimit() {
        return new Class[] {String.class};
    }

    @Override
    protected void load(Object... args) {
        String orderBy = args[0].toString();

        this.orderBy = orderBy;
    }

    @Override
    protected void doCast(EsViewDTO viewDTO, EsBaseDTO baseDTO) {
        if (StringUtils.isNotBlank(orderBy)) {
            String[] orderByArr = orderBy.split(" ");
            String orderField = orderByArr[0];
            String orderMethodStr = orderByArr[1].toUpperCase();
            SortOrder orderMethod = SortOrder.Desc;
            if ("ASC".equals(orderMethodStr)) {
                orderMethod = SortOrder.Asc;
            }

            new EsFieldSortParam(orderField, orderMethod).addTo(baseDTO);
        }
    }
}
